package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.util.LiveAutoAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Override
	public LiveRoom getCurrentLive() {
		//获取用户id
		Long userId = AuthContextHolder.getUserId();
		//查询
		LambdaQueryWrapper<LiveRoom> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(LiveRoom::getUserId, userId);
		wrapper.gt(LiveRoom::getExpireTime, new Date());
		LiveRoom liveRoom = liveRoomMapper.selectOne(wrapper);
		return liveRoom;
	}

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo) {
		LiveRoom currentLive = getCurrentLive();
		if(currentLive != null){
			return currentLive;
		}
		// 获取用户id
		Long userId = AuthContextHolder.getUserId();

		LiveRoom liveRoom = new LiveRoom();
		liveRoom.setUserId(userId);
		liveRoom.setCoverUrl(liveRoomVo.getCoverUrl());
		liveRoom.setLiveTitle(liveRoomVo.getLiveTitle());
		liveRoom.setViewCount(0);
		liveRoom.setStatus("1");
		liveRoom.setTagId(liveRoomVo.getTagId());

		liveRoom.setAppName("live");
		liveRoom.setStreamName("room");
		TencentLiveAddressVo tencentLiveAddressVo = LiveAutoAddressUtil.getAddressUrl("room", liveRoomVo.getExpireTime().getTime() / 1000);
		liveRoom.setPushUrl(tencentLiveAddressVo.getPushWebRtcUrl());
		liveRoom.setPlayUrl(tencentLiveAddressVo.getPullWebRtcUrl());

		liveRoom.setLongitude(liveRoom.getLongitude());
		liveRoom.setLatitude(liveRoomVo.getLatitude());
		liveRoom.setLocation(liveRoom.getLocation());
		liveRoom.setExpireTime(liveRoomVo.getExpireTime());
		liveRoomMapper.insert(liveRoom);
		log.info("直播间数据添加成功");
		return liveRoom;
	}

	@Override
	public List<LiveRoom> findLiveList() {
		LambdaQueryWrapper<LiveRoom> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.gt(LiveRoom::getExpireTime, new Date());
		List<LiveRoom> liveRoomList = liveRoomMapper.selectList(queryWrapper);
		return liveRoomList;
	}
}
